﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Vit.Common;
using Vit.Web;
using Vit.Web.Models;
using Vit.Web.Providers.Data;
using Vit.Web.Helpers;

namespace Vit.AdminModule.Areas.Admin.Providers
{
    public class SqlWebPageDataProvider : DbContextDataProvider<WebProvidersDb, Vit.Web.Models.WebPage>
    {
        protected override IQueryable<Vit.Web.Models.WebPage> OrderByDefault(IQueryable<Vit.Web.Models.WebPage> query)
        {
            return query.OrderBy(o => o.Name);
        }

        public override object[] GetKeys(Vit.Web.Models.WebPage obj)
        {
            return new object[] { obj.Name };
        }

        public override Vit.Web.Models.WebPage GetByKeys(params object[] ids)
        {
            if (ids == null || ids.Length != 1)
                return null;
            string key = ids[0].ToString();
            return db.Pages.FirstOrDefault(o => o.Name == key);
        }

        public override Vit.Web.Models.WebPage SetDefaultValues(Vit.Web.Models.WebPage obj)
        {
            if (obj.WebSite == null)
            {
                obj.WebSite = PortalContext.Current.Site;
            }
            return obj;
        }

        public override Vit.Web.Models.WebPage New()
        {
            string name = System.Web.HttpContext.Current.Request.Path;
            WebSite site = PortalContext.Current.Site;
            return new WebPage()
            {
                Name = name,
                UrlPattern = name,
                CharSet = site.DefaultCharSet,
                CultureInfo = site.CultureInfo,
                MetaKeywords = site.DefaultMetaKeywords,
                MetaDescription = site.DefaultMetaDescription,
                Title = site.DefaultTitle,
                MatchPriority = 99999,
                WebSite = site
            };
        }
    }
}
